<template>
  <block>
    <view class="search-wrapper">
      <uni-search-bar
        @input="input"
        @confirm="searchHandler"
        :radius="15"
        placeholder="搜索"
        cancelButton="none"
        :focus="true"
      />
    </view>

    <scroll-view scroll-y>
      <view
        class="search-list"
        v-for="(item, id) in searchList"
        :key="id"
        @click="gotoGoodsDetail(item.goods_id)"
      >
        <view
          class="goods-name"
          hover-class="none"
          hover-stop-propagation="false"
        >
          {{ item.goods_name }}
        </view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>

      <view class="search-history" v-if="searchList.length == 0">
        <view class="history-title">
          <text> 搜索历史 </text>
          <uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
        </view>
        <view class="history-list" v-for="(item, id) in historys" :key="id">
          <uni-tag :text="item" @click="gotoGoodsList(item)"> </uni-tag>
        </view>
      </view>
    </scroll-view>
  </block>
</template>

<script>
export default {
  name: "search",
  props: {},
  data() {
    return {
      searchContent: "", // 搜索内容
      timer: null, // 延时器
      searchList: [], // 搜索结果列表
      historyList: [], // 搜索记录列表
    };
  },
  computed: {
    historys() {
      return [...this.historyList].reverse();
    },
  },
  methods: {
    input(e) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.searchContent = e;
        if (this.searchContent.length === 0) {
          this.searchList = [];
        } else {
          this.getSearchList();
        }
      }, 500);
    },
    // 发送请求获取搜索列表
    async getSearchList() {
      const res = await uni.$http.get(`/api/public/v1/goods/search?`, {
        query: this.searchContent,
      });
      if (res.statusCode !== 200) return uni.$showMessage();
      this.searchList = res.data.message.goods;
      this.saveSearchHistory();
    },
    gotoGoodsDetail(goods_id) {
      uni.navigateTo({
        url: `/subpkg/goods_detail/index?goods_id=${goods_id}`,
      });
    },
    saveSearchHistory() {
      const set = new Set(this.historyList);
      set.delete(this.searchContent);
      set.add(this.searchContent);
      this.historyList = Array.from(set);

      // 将搜索记录本地存储化
      uni.setStorageSync("searchHistory", JSON.stringify(this.historyList));
    },
    // 清空历史记录
    clearHistory() {
      if (this.historyList.length !== 0) {
        uni.showModal({
          title: "提示",
          content: "你真的要删除搜索历史记录么？",
          success: (res) => {
            if (res.confirm) {
              uni.removeStorageSync("searchHistory");
              this.historyList = [];
            } else if (res.cancel) {
            }
          },
        });
      } else {
        uni.showToast({ title: "历史记录已经是空的", icon: "none" });
      }
    },
    // 通过历史记录去到商品列表
    gotoGoodsList(item) {
      uni.navigateTo({
        url: `/subpkg/goods_list/index?cid=${item}`,
      });
    },
  },
  watch: {},

  // 组件周期函数--监听组件挂载完毕
  mounted() {
    this.historyList = JSON.parse(uni.getStorageSync("searchHistory") || "[]");
  },
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {},
};
</script>

<style scoped lang="scss">
.search-wrapper {
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-list {
  height: 30px;
  padding: 0 5px;
  box-sizing: border-box;
  line-height: 30px;
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid #efefef;
  justify-content: space-between;
  .goods-name {
    font-size: 12px;
    width: 95%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.search-history {
  padding: 5px;
  .history-title {
    font-size: 12px;
    height: 30px;
    line-height: 30px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    margin: 5px;
    display: inline-block;
  }
}
</style>